package com.sxt.core.provider.method;

import java.lang.reflect.Method;

import com.sxt.core.anno.AutoBuilder;
import com.sxt.core.context.IocContext;
import com.sxt.core.model.Request;
import com.sxt.core.model.Response;
import com.sxt.core.provider.InvokeLocalMethod;

@AutoBuilder
public class IocObjectInvoker implements InvokeLocalMethod {

	private IocContext iocContext;

	public IocObjectInvoker() {
	
	}
	
	@Override
	public Response execute(Request request) {

		Response response = new Response();

		String interfaces = request.getInterfaceName();
		Class<?> type  =  null;
		Object[] agrs = request.getAgrs();
		try {
			type = Class.forName(interfaces);

			// 通过接口来获去ioc、里面的对象
			Object realObject = iocContext.getBean(type);

			String methodName = request.getMethodName();
			Class<?> []types = null ;
			if(agrs!=null) {
				types= new Class<?>[agrs.length];
				for (int i = 0; i < types.length; i++) {
					types[i] = agrs[i].getClass();
				}
			}
			Method realMethod = null ;
			if(types==null) {
				realMethod = realObject.getClass().getMethod(methodName);
			}else {
				realMethod = realObject.getClass().getMethod(methodName, types);
			}
			Object object = realMethod.invoke(realObject, agrs);
			response.setResult(object);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			response.setError(e);
		}
		return response;
	}
	public void setIocContext(IocContext iocContext) {
		this.iocContext = iocContext;
	}

}
